package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import entity.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.List;


@Service
public class SpitService  {

    @Autowired
    private SpitDao spitDao;
    @Autowired
    private IdWorker idWorkerl;
    @Autowired
    private MongoTemplate mongoTemplate;

    //1.查询所有吐槽列表
    public List<Spit> findAll() {
        return spitDao.findAll();
    }
    //2.根据id查询吐槽列表
    public Spit findById(String spitId) {
        return spitDao.findById(spitId).get();
    }

    //3.添加吐槽
    public void insert(Spit spit){
        //1为吐槽对象设置id
        spit.set_id(idWorkerl.nextId()+"");
        //2.插入数据库
        spitDao.insert(spit);

    }
    //4.修改吐槽
    public void update(Spit spit) {
        //1.执行修改
      spitDao.save(spit);
    }
    //5.根据id删除吐槽
    public void delete(String spitId) {
        //1.执行删除
        spitDao.deleteById(spitId);

    }
    //6.根据父id查询吐槽列表
    public PageResult<Spit> findByParentId(String parentid, int page, int size) {
        //1.调用dao层根据父id进行查询
        Page<Spit> spitPage = spitDao.findByParentid(parentid, PageRequest.of(page-1, size));
        //2.返回结果
        return new PageResult<>(spitPage.getTotalElements(),spitPage.getContent());
    }
    //7.进行吐槽点赞
    public void thumbup(String spitId) {
       //1.方法一：
        //1.1查询出吐槽对象
//        Spit spit = spitDao.findById(spitId).get();
//        //1.2将该对象的点赞数进行+1
//        spit.setThumbup(spit.getThumbup()+1);
//        //1.3保存进数据库
//        spitDao.save(spit);
        //2.方法二
        //2.1定义查询对象
        Query query = new Query();
        //2.2添加条件
        query.addCriteria(Criteria.where("_id").is(spitId));
        //2.3定义修改对象
        Update update = new Update();
        update.inc("thumbup",1);
        //2.4执行修改
        mongoTemplate.updateFirst(query,update,"spit");


    }
}
